package com.leyou.user.web;

import com.leyou.auth.dto.UserDetails;
import com.leyou.auth.local.UserContext;
import com.leyou.common.exceptions.LyException;
import com.leyou.user.dto.UserDTO;
import com.leyou.user.entity.User;
import com.leyou.user.service.UserService;
import jdk.nashorn.internal.objects.annotations.Getter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.stream.Collectors;

@RestController
@RequestMapping("info")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     *  判断信息是否存在
     * @param data  数据信息
     * @param type  数据类型：1.用户名 2.号码
     * @return  是否存在
     */
    @GetMapping("exists/{data}/{type}")
    public ResponseEntity<Boolean> exists(@PathVariable("data") String data ,@PathVariable("type") Integer type){
        //校验数据
        return ResponseEntity.ok(userService.DataTypeExists(data,type));
    }

    /**
     *  发送短信获取验证码
     * @param phone  手机号码
     * @return 无
     */
    @PostMapping("/code")
    public ResponseEntity<Void> sendCode (@RequestParam("phone") String phone){
        //根据号码发送短信
        userService.sendCode(phone);
        //返回无数据
        return ResponseEntity.noContent().build();
    }

    /**
     *  注册
     * @param user 用户信息
     * @param code 验证码
     * @return 无
     */
    @PostMapping
    public  ResponseEntity<Void> register (@Valid User user , BindingResult bindingResult, @RequestParam("code") String code){
        //校验用户名，号码，密码
        if (bindingResult.hasErrors()){
            String map = bindingResult.getFieldErrors().stream()
                    .map(FieldError::getDefaultMessage).collect(Collectors.joining(","));
            //返回错误
            throw new LyException(400 , "请求参数有误" + map);
        }
        //根据用户信息和验证码登录
        userService.register(user ,code);
        //无返回值
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

    /**
     *  用户名和密码查询
     * @param username 用户名
     * @param password  密码
     * @return  用户信息
     */
    @GetMapping
    public ResponseEntity<UserDTO> queryUserByUsernameAndPassword(
            @RequestParam("username") String username,
            @RequestParam("password") String password){
        //查询后返回
        return ResponseEntity.ok(userService.queryUserByUsernameAndPassword(username,password));
    }

    /**
     * 获取主界面登录信息
     * @return
     */
    @GetMapping("me")
    public ResponseEntity<UserDetails> whoIsLogin(){
        return ResponseEntity.ok(UserContext.getUser());
    }
}
